/**
 * ajax请求配置
 */
import Vue from 'vue'
import axios from 'axios'
import { store } from '../store/store'
import router from '../router/index'
// import Qs from 'qs'

// axios默认配置
axios.defaults.timeout = 10000   // 超时时间

// 整理数据

// 路由请求拦截
// http request 拦截器
axios.interceptors.request.use(
  config => {
    if (config.url != "/api/book/list" || config.url != "/api/book/list" || config.url != "/api/libraryReader/reg-reader") {
      if (store.state.access_token) {
        config.headers['Authorization'] = 'Bearer ' + store.state.access_token
      }
    }
    Vue.$vux.loading.show({
      text: '数据加载中'
    })
    return config
  },
  error => {
    Vue.$vux.loading.hide()
    return Promise.reject(error.response)
  })

// 路由响应拦截
// http response 拦截器
axios.interceptors.response.use(
  response => {
    // console.log(response)
    if (response.data.code == '401') {
      Vue.$vux.alert.show({
        title: '提示',
        content: '登录过期,请重新登录',
        onShow() {
        },
        onHide() {
          // eslint-disable-next-line no-undef
          router.replace({
            path: '/login'
          })
          location.reload()
        }
      })
    }
    if (response.data.status) {
      // eslint-disable-next-line eqeqeq
      if (response.data.status != 0) {
        // const msg = '请求失败,' + response.data.message
        // Vue.$vux.toast.show({
        //   text: msg, type: 'warn'
        // })
      }
    }
    Vue.$vux.loading.hide()
    return response
  },
  error => {
    Vue.$vux.loading.hide()
    if (error.response) {
      switch (error.response.status) {
        case 401:
          // 返回 401 清除token信息并跳转到登录页面
          Vue.$vux.alert.show({
            title: '提示',
            content: '登录过期,请重新登录',
            onShow() {
            },
            onHide() {
              // eslint-disable-next-line no-undef
              router.replace({
                path: '/login'
              })
              location.reload()
            }
          })
          break
        case 404:
          Vue.$vux.toast.show({
            text: '请求失败!', type: 'warn'
          })
          break
        default:
          Vue.$vux.toast.show({
            text: '请求失败!', type: 'warn'
          })
          break
      }
    }
    console.log('error' + error.response)
    return Promise.reject(error.response)   // 返回接口返回的错误信息
  })
export default axios
